package com.java.basis.thread;

/**
 * Thread和Runnable的实质是继承关系，没有可比性。无论使用Runnable还是Thread，都会new
 * Thread，然后执行run方法。用法上，如果有复杂的线程操作需求，那就选择继承Thread，如果只是简
 * 单的执行一个任务，那就实现runnable。
 */
public class ThreadTest {
    //原因是：MyThread创建了两个实例，自然会卖出两倍，属于用法错误
    //会卖出多一倍的票
    public static void main(String[] args) {
        new MyThread().start();
        new MyThread().start();
        //如果不想多一倍，使用以下方式
//        MyThread myThread = new MyThread();
//        new Thread(myThread).start();
//        new Thread(myThread).start();

    }

    static class MyThread extends Thread {
        private int ticket = 5;

        public void run() {
            while (true) {
                System.out.println("name= " + Thread.currentThread().getName() + " Thread ticket = " + ticket--);
                if (ticket < 0) {
                    break;
                }
            }
        }
    }
}

class RunnableTest {
    //正常卖出
    public static void main(String[] args) {
        MyThread2 myThread2 = new MyThread2();
        new Thread(myThread2).start();
        new Thread(myThread2).start();

    }

    static class MyThread2 implements Runnable{
        private int ticket = 5;
        public void run(){
            while(true){
                System.out.println("name= " + Thread.currentThread().getName() + " Runnable ticket = " + ticket--);
                if(ticket < 0){
                    break;
                }
            }
        }
    }
}
